package com.laf.framework.security.filter;

import com.laf.common.core.domain.model.LoginMobileUser;
import com.laf.common.core.domain.model.LoginUser;
import com.laf.common.utils.SecurityUtils;
import com.laf.common.utils.StringUtils;
import com.laf.framework.web.service.TokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * token过滤器 验证token有效性
 *
 * @author ruoyi
 */
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter
{

    @Autowired
    private TokenService tokenService;

    // 令牌自定义标识
    @Value("${token.header}")
    private String header;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
            throws ServletException, IOException {
        // TODO 分别 pc 端 和 移动端 进行拦截认证
        String token = request.getHeader(header);
        // 判断token 是否以 Bearer 开头 ，如果是就是 PC 端 否则就是移动端
        if (StringUtils.isNotEmpty(token) && token.startsWith("Bearer")) {
            // PC 端
            LoginUser loginUser = tokenService.getLoginUser(request);
            if (StringUtils.isNotNull(loginUser) && StringUtils.isNull(SecurityUtils.getAuthentication())) {
                tokenService.verifyToken(loginUser);
                UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginUser, null, loginUser.getAuthorities());
                authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                SecurityContextHolder.getContext().setAuthentication(authenticationToken);
            }
            chain.doFilter(request, response);

        } else if (StringUtils.isNotEmpty(token)) {
            // 移动端
            LoginMobileUser loginMobileUser = tokenService.getLoginMobileUser(request);
            if (StringUtils.isNotNull(loginMobileUser) && StringUtils.isNull(SecurityUtils.getAuthentication())) {
                tokenService.verifyTokenMobile(loginMobileUser);
                // UsernamePasswordAuthenticationToken 创建必须要三个参数，只有是三个参数的中构造方法才会将用户标记为已登录 super.setAuthenticated(true);
                UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginMobileUser, null, loginMobileUser.getAuthorities());
                authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                SecurityContextHolder.getContext().setAuthentication(authenticationToken);
            }
            chain.doFilter(request, response);
        } else {
            // 没有token 直接放行
            chain.doFilter(request, response);
        }


    }
}
